package ua.kharkov.knure.pereverziev.diploma.pathfinder;

import java.sql.Time;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.FlightsService;
import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Airport;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Flight;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Route;

public class PathFinder {

	private static final Logger log = Logger.getLogger(PathFinder.class);

	@SuppressWarnings("deprecation")
	public static List<Route> FindPaths(final Airport departureAirport,
			final Airport destinationAirport, final java.util.Date date) {

		log.debug("************\n\n Start finding path "
				+ (new Time(24, 0, 0)).getTime());

		final List<Route> result = new LinkedList<Route>();

		final FlightsService flightService = ServiceFactory.getInstance()
				.getFlightsService();

		final List<Flight> flightsDep = flightService.getDeparturesFlights(
				departureAirport, date);

		log.debug("Found flights from departure:\n" + flightsDep);

		final List<Flight> flightsArriv = flightService.getDestinationFlights(
				destinationAirport, date);

		log.debug("Found flights to arrival:\n" + flightsArriv);

		List<Flight> flights = new ArrayList<Flight>(2);

		for (final Flight fDep : flightsDep) {
			for (final Flight fAriv : flightsArriv) {

				final java.util.Date arrival = new java.util.Date(fDep
						.getFlightDate().getTime()
						+ fDep.getSchedule().getDepartureTime().getTime()
						+ fDep.getSchedule().getFlight_duration().getTime());
				final java.util.Date departure = new java.util.Date(fAriv
						.getFlightDate().getTime()
						+ fAriv.getSchedule().getDepartureTime().getTime());

				final Long difference = arrival.getTime() - departure.getTime();

				if (fDep.getSchedule().getDestination().getId()
						.equals(fAriv.getSchedule().getDeparture().getId())
						&& (difference > -86400000) && difference < 0) {

					flights = new ArrayList<Flight>(2);
					flights.add(fDep);
					flights.add(fAriv);
					result.add(new Route(flights));

					log.debug("Found suitable connections:" + fDep.getId()
							+ " - " + fAriv.getId());
				}
			}
		}
		return result;
	}

}
